import 'package:flutter/material.dart';
import 'package:flutter_music/utils/audio_player.dart';
import 'package:flutter_music/widgets/drawer.dart';
import 'package:flutter_music/pages/home/widgets/home_song_item.dart';
import 'package:flutter_music/pages/music/music.dart';
import 'package:provider/provider.dart';

import 'providers/songs_provider.dart';

class HomePage extends StatefulWidget {
  const HomePage({
    super.key,
  });

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late SongsProvider _songsProvider;

  @override
  void initState() {
    _songsProvider = Provider.of<SongsProvider>(context, listen: false);
    // 初始化播放器
    AudioPlayerUtils.initAudioPlayer();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.background,
      appBar: AppBar(title: const Text('P L A Y L I S T')),
      drawer: const HomeDrawer(),
      body: Consumer<SongsProvider>(
        builder: (context, provider, child) {
          final songs = provider.songs;

          return ListView.builder(
            itemCount: songs.length,
            itemExtent: 80,
            itemBuilder: (context, index) => Container(
              margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
              child: HomeSongItem(
                song: songs[index],
                onTap: () => _goMusicPage(index),
              ),
            ),
          );
        },
      ),
    );
  }

  void _goMusicPage(int currentIndex) {
    _songsProvider.currentPlayIndex = currentIndex;
    // to music page
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const MusicPage()),
    );
  }
}
